using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class ChatPanel : UIBase
{
    private readonly float widthPerChar = 17f;
    private readonly float leftOffset = 7f;
    private readonly float rightOffset = 7f;

    private CanvasGroup canvasGroup;
    private RectTransform bg;
    private Text showLabel;
    private Sequence seq;

    protected override void Awake()
    {
        base.Awake();
        canvasGroup = GetComponent<CanvasGroup>();
        bg = GetComponent<RectTransform>();
        showLabel = GetComponentInChildren<Text>();
        canvasGroup.alpha = 0;
        seq = DOTween.Sequence().SetAutoKill(false).Pause();
        seq.PrependCallback(() => canvasGroup.alpha = 1);
        seq.AppendInterval(1f);
        seq.Append(DOTween.To((t) => { canvasGroup.alpha = t; }, 1, 0,0.5f));
    }

    public void Show(string chat)
    {
        SetBGWidth(chat);
        showLabel.text = chat;
        seq.Restart();
    }
    
    private void SetBGWidth(string str)
    {
        float charCount = str.Length;
        bg.sizeDelta = new Vector2(charCount * widthPerChar + leftOffset + rightOffset, bg.sizeDelta.y);
    }

    private void OnDisable()
    {
        DOTween.Kill(seq);
    }
}
